package com.lzj.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzj.admin.query.RoleQuery;
import com.lzj.admin.pojo.Role;
import com.lzj.admin.mapper.RoleMapper;
import com.lzj.admin.pojo.RoleMenu;
import com.lzj.admin.service.IRoleMenuService;
import com.lzj.admin.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzj.admin.utils.AssertUtil;
import com.lzj.admin.utils.PageResultUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author lvyuanbo
 * @since 2021-08-10
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Resource
    private IRoleMenuService roleMenuService;

    /**
     * @param userId
     * @Description: 添加|编辑用户列表的角色栏
     * @Author: lvyuanbo
     * @Date: 2021/8/13
     */
    @Override
    public List<Map<String, Object>> queryAllRoles(Integer userId) {
        return  this.baseMapper.queryAllRoles(userId);
    }

    /**
     * @param roleQuery
     * @Description: 查看权限列表
     * @Author: lvyuanbo
     * @Date: 2021/8/13
     */
    @Override
    public Map<String, Object> roleList(RoleQuery roleQuery) {
        IPage<Role> page = new Page<>(roleQuery.getPage(), roleQuery.getLimit());
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_del", 0);
        if (StringUtils.isNotBlank(roleQuery.getRoleName())) {
            queryWrapper.like("name", roleQuery.getRoleName());
        }
        page = this.baseMapper.selectPage(page, queryWrapper);
        return PageResultUtil.getResult(page.getTotal(), page.getRecords());

    }

    /**
     * @param role
     * @Description: 保存角色
     * @Author: lvyuanbo
     * @Date: 2021/8/13
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void saveRole(Role role) {
        AssertUtil.isTrue(StringUtils.isEmpty(role.getName()), "角色名称不能为空");
        AssertUtil.isTrue(null != this.findUserByUserName(role.getName()), "角色名称已存在");
        role.setIsDel(0);
        AssertUtil.isTrue(!this.save(role), "角色记录添加失败");
    }

    /**
     * @param role
     * @Description: 更新角色
     * @Author: lvyuanbo
     * @Date: 2021/8/13
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void updateRole(Role role) {
        AssertUtil.isTrue(StringUtils.isEmpty(role.getName()), "角色名称不能为空");
        Role temp = this.findUserByUserName(role.getName());
        AssertUtil.isTrue(null != temp && !(temp.getId().equals(role.getId())), "角色名称已存在");
        AssertUtil.isTrue(!this.updateById(role), "角色记录更新失败");
    }

    @Override
    public Role findUserByUserName(String name) {
        return this.baseMapper.selectOne(new QueryWrapper<Role>().eq("is_del", 0).eq("name", name));
    }

    /**
     * @param id
     * @Description: 删除角色
     * @Author: lvyuanbo
     * @Date: 2021/8/13
     */
    @Override
    public void deleteRole(Integer id) {
        AssertUtil.isTrue(null == id, "待删除的角色不能为空");
        Role role = this.getById(id);
        role.setIsDel(1);
        AssertUtil.isTrue(!this.updateById(role), "角色记录删除失败!");
    }

    /**
     * 角色授权接口
     *
     * @param roleId
     * @param mids
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void addGrant(Integer roleId, Integer[] mids) {
        /**
         * 1.参数校验
         *    roleId 非空 必须存在
         * 2.授权
         *    2.1 第一次授权
         *        直接批量添加即可
         *    2.2 第2+次  授权
         *        如果存在原始权限  此时删除原始权限  然后添加新的权限记录
         *        如果不存在 直接批量添加即可
         *  合并2.1 2.2 原始权限不管是否存在  先执行权限记录查询 如果存在 直接删除(根据角色id)
         *  执行批量添加(数组非空 数量>0)
         */
        Role role = this.getById(roleId);
        AssertUtil.isTrue(null == role,"参数异常");
        int count = roleMenuService.count(new QueryWrapper<RoleMenu>().in("role_id", roleId, Arrays.asList(mids)));
        if(count>0){
            AssertUtil.isTrue(!roleMenuService.remove(new QueryWrapper<RoleMenu>().in("role_id",roleId,Arrays.asList(mids))),"删除权限失败");
        }
        if(StringUtils.isNotBlank(String.valueOf(mids))){
            //新增
            List<RoleMenu> menus=new ArrayList<>();
            for(Integer s:mids){
                RoleMenu roleMenu=new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(s);
                menus.add(roleMenu);
            }
            AssertUtil.isTrue(!(roleMenuService.saveBatch(menus)),"角色授权失败!");
        }


    }
}
